<template>
  <n-card class="w-screen h-screen">
    <div class="h-full w-full flex items-center justify-center">
      <div class="absolute top-10 left-10">
        <theme-change-button/>
      </div>
      <div class="w-96">
        <n-card bordered>
          <template #header>
            <div>
              <n-h2 align-text>登录</n-h2>
            </div>
          </template>
          <n-form ref="loginFormRef" :model="loginForm.value" :rules="loginFormRules">
            <n-form-item path="username">
              <n-input placeholder="请输入账号" v-model:value="loginForm.value.username"></n-input>
            </n-form-item>
            <n-form-item path="password">
              <n-input placeholder="请输入密码" v-model:value="loginForm.value.password" type="password"></n-input>
            </n-form-item>
            <n-form-item>
              <n-button style="width: 100%" type="primary" @click="login">登录</n-button>
            </n-form-item>
          </n-form>
        </n-card>
      </div>
    </div>
  </n-card>
</template>

<script setup>
import {useMessage} from "naive-ui";
import {ThemeChangeButton} from "../components/index.js";
import {useThemeStore} from "../store/theme/index.js";
import {login as userLogin} from "../apis/sys/user/index.js";
import {reactive, ref} from "vue";
import {useSysUserStore} from "../store/sys-user/index.js";
import {useRouter} from "vue-router";

const themeStore = useThemeStore()
const sysUserStore = useSysUserStore()
const message = useMessage()
const router = useRouter()
const loginFormRef = ref(null)
const loginForm = reactive({
  value: {
    username: 'admin',
    password: 'admin',
    rememberMe: false
  }
})
const loginFormRules = reactive({
  username: {
    required: true,
    message: '请输入账户名',
    trigger: ['input']
  },
  password: {
    required: true,
    message: '请输入密码',
    trigger: ['input']
  }
})

const login = async () => {
  loginFormRef.value?.validate(async (errors) => {
    if (!errors) {
      const res = await userLogin(loginForm.value.username, loginForm.value.password, loginForm.value.rememberMe)
      if (res.data.code === 1) {
        const tokenInfo = res.data.data
        await sysUserStore.login(tokenInfo)
        await message.success("登录成功！")
        await router.replace({
          name: 'Home'
        })
      }
    }
  })
}
</script>


<style scoped>

</style>
